import router from '@/router'
import store from '@/store'

const whiteList = [
    'Login'
]

//增加一个标识：是否已经添加过动态路由了
let hasRouter = false

router.beforeEach(async (to,from,next) => {

    //1、白名单
    if(whiteList.includes(to.name)){
        next()
    }

    //2、权限校验，是否已经登录
    //token不存在，跳转到登录页面
    if(!store.getters.token){
        next('/login')
    }

    //3、获取用户信息
    let userInfo = store.getters.userInfo
    if(!userInfo || JSON.stringify(userInfo) === '{}'){
        await store.dispatch('getUserInfo')
    }

    //4、根据菜单动态生成路由
    console.log('store.getters.menuList',store.getters.menuList)
    if (!hasRouter) {
        //没有添加过动态路由，才去添加
        addRouter(store.getters.menuList)
        hasRouter = true
        next({...to,replace:true})
    }

    next()
})

//现有的路由
let newRoutes = router.options.routes
const addRouter = menuList => {
    menuList.forEach(menu => {
        //1、menu转换为router
        let route = menuToRoute(menu)
        if (route) {
            //2、如果router为空，说明是目录不用添加，
            // 如果router不为空，添加到Layout的children里面
            router.addRoute('Layout',route)
            newRoutes[0].children.push(route)
        }

        //3、递归调用
        if(menu.children){
            addRouter(menu.children)
        }
    })
}

//vite动态获取所有的组件
const modules = import.meta.glob('./views/*/*/*.vue')

//menu转换为router
const menuToRoute = menu => {

    if(!menu.component){
        return null
    }

    let route = {
        path: menu.path,
        name: menu.name,
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    }
    route.component = modules['./views/' + menu.component]
    return route
}
